package com.example.iotmanagerment26.mapper;

import com.example.iotmanagerment26.domain.Device;
import com.example.iotmanagerment26.domain.DeviceLocation;
import com.example.iotmanagerment26.domain.DeviceWithLocation;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface DeviceMapper {
    @Select("select * from device where id=#{id}")
    Device selectDeviceById(int id);

    //@Select("select * from device")
    @Select("SELECT " +
            "d.id AS deviceId, " +
            "d.userCount, " +
            "d.name, " +
            "d.type, " +
            "d.description, " +
            "d.createTime, " +
            "dl.id AS locationId, " +
            "dl.device AS deviceName, " +
            "dl.latitude, " +
            "dl.longitude, " +
            "dl.location " +
            "FROM device d " +
            "LEFT JOIN device_location dl ON d.name = dl.device")
    List<DeviceWithLocation> selectAllDevice();

    @Insert("insert into device values (null,#{name},#{type},#{description},#{createTime},#{userCount})")
    @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
    int insertDevice(Device device);

    @Delete("delete from device where id=#{id}")
    int deleteDeviceById(int id);

    @Select("select * from device where name=#{name}")
    Device selectDeviceByName(String name);

    @Update("update device set name=#{name},type=#{type},description=#{description},createTime=#{createTime},userCount=#{userCount} where id=#{id}")
    int updateInfoById(Device device);

    @Update("update device set userCount= userCount +1 where name=#{name}")
    int updateDevice(Device device);

    @Update("update device set userCount= userCount -1 where name=#{name}")
    int reduceUserCount(String name);

    @Select("select * from device_location")
    List<DeviceLocation> selectAllDeviceLocation();
}
